const https = require('https');
const http = require('http');
const fs = require('fs');
const { URL } = require('url');

// API 基础 URL
const API_BASE = 'http://localhost:8080';

// 测试用户地址
const CREATOR_ADDRESS = 'shTdKtBScJMC4GkKmasiE9iMKrtZnMFUtwVTdSXsKac';

/**
 * 简单的HTTP请求函数
 */
function makeRequest(url, options = {}) {
  return new Promise((resolve, reject) => {
    const urlObj = new URL(url);
    const isHttps = urlObj.protocol === 'https:';
    const lib = isHttps ? https : http;
    
    const reqOptions = {
      hostname: urlObj.hostname,
      port: urlObj.port || (isHttps ? 443 : 80),
      path: urlObj.pathname + urlObj.search,
      method: options.method || 'GET',
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      },
      timeout: options.timeout || 60000
    };

    const req = lib.request(reqOptions, (res) => {
      let data = '';
      
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        try {
          const response = {
            status: res.statusCode,
            data: JSON.parse(data)
          };
          resolve(response);
        } catch (error) {
          resolve({
            status: res.statusCode,
            data: data
          });
        }
      });
    });

    req.on('error', (error) => {
      reject(error);
    });

    req.on('timeout', () => {
      req.destroy();
      reject(new Error('Request timeout'));
    });

    if (options.data) {
      req.write(JSON.stringify(options.data));
    }

    req.end();
  });
}

/**
 * 创建完整功能的代币
 */
async function createAdvancedToken() {
  console.log('🚀 创建高级功能代币...\n');

  const tokenData = {
    // 基本信息
    name: '高级测试代币',
    symbol: 'ADVANCED',
    decimals: 9,
    supply: '1000000000', // 10亿代币
    description: '这是一个包含所有功能的高级测试代币，支持靓号地址、社交链接和权限控制。',
    creator: CREATOR_ADDRESS,

    // 靓号地址配置
    enablePrettyAddress: true,
    prettyPrefix: '88',
    prettySuffix: '',
    caseSensitive: false,
    threads: 1,

    // 社交链接
    website: 'https://example.com',
    twitter: 'https://twitter.com/example',
    telegram: 'https://t.me/example',
    discord: 'https://discord.gg/example',

    // 权限控制
    revokeUpdateAuthority: false,
    revokeFreezeAuthority: true,
    revokeMintAuthority: true,
  };

  try {
    console.log('📊 代币配置:');
    console.log(`- 名称: ${tokenData.name}`);
    console.log(`- 符号: ${tokenData.symbol}`);
    console.log(`- 精度: ${tokenData.decimals}`);
    console.log(`- 供应量: ${Number(tokenData.supply).toLocaleString()}`);
    console.log(`- 靓号前缀: "${tokenData.prettyPrefix}"`);
    console.log(`- 权限设置: 冻结权限撤销=${tokenData.revokeFreezeAuthority}, 铸币权限撤销=${tokenData.revokeMintAuthority}\n`);

    console.log('⏳ 发送创建请求...');
    
    const response = await makeRequest(`${API_BASE}/api/tokens`, {
      method: 'POST',
      data: tokenData,
      timeout: 600000 // 60秒超时，因为靓号生成可能需要时间
    });

    if (response.data.success) {
      const { token, transaction } = response.data.data;
      
      console.log('\n✅ 代币创建成功！');
      console.log('=====================================');
      console.log(`📍 代币地址: ${token.mint}`);
      console.log(`🏷️  名称: ${token.name} (${token.symbol})`);
      console.log(`💰 供应量: ${Number(token.supply).toLocaleString()}`);
      console.log(`🎯 精度: ${token.decimals}`);
      console.log(`👤 创建者: ${token.creator}`);
      
      if (token.isPrettyAddress) {
        console.log('\n🎨 靓号地址信息:');
        console.log(`- 前缀: "${token.prettyPrefix}"`);
        console.log(`- 生成统计: ${JSON.stringify(token.prettyConfig, null, 2)}`);
      }
      
      console.log('\n🔗 社交链接:');
      console.log(`- 官网: ${token.website || '未设置'}`);
      console.log(`- Twitter: ${token.twitter || '未设置'}`);
      console.log(`- Telegram: ${token.telegram || '未设置'}`);
      console.log(`- Discord: ${token.discord || '未设置'}`);
      
      console.log('\n🔐 权限状态:');
      console.log(`- 更新权限: ${token.isUpdateRevoked ? '已撤销' : '保留'}`);
      console.log(`- 冻结权限: ${token.isFreezeRevoked ? '已撤销' : '保留'}`);
      console.log(`- 铸币权限: ${token.isMintRevoked ? '已撤销' : '保留'}`);
      
      console.log('\n📋 交易信息:');
      console.log(`- 交易大小: ${transaction.transaction ? transaction.transaction.length : 'N/A'} 字符 (base64)`);
      if (transaction.mintKeypair) {
        console.log(`- Mint密钥: [${transaction.mintKeypair.slice(0, 8).join(', ')}...]`);
      }
      
      if (transaction.prettyAddressInfo) {
        console.log(`- 靓号生成: ${transaction.prettyAddressInfo.attempts} 次尝试，耗时 ${transaction.prettyAddressInfo.timeElapsed}ms`);
      }
      
      console.log('\n🔍 区块链链接:');
      console.log(`- Solana Explorer: https://explorer.solana.com/address/${token.mint}?cluster=devnet`);
      
      // 保存详细信息到文件
      const tokenInfo = {
        token,
        transaction,
        timestamp: new Date().toISOString(),
        createdBy: 'advanced-token-creation-test'
      };
      
      fs.writeFileSync(`advanced-token-${token.symbol}-${Date.now()}.json`, JSON.stringify(tokenInfo, null, 2));
      console.log(`\n💾 详细信息已保存到文件`);
      
      return tokenInfo;
      
    } else {
      console.error('❌ 代币创建失败:', response.data.error);
      return null;
    }

  } catch (error) {
    console.error('❌ 请求失败:', error.message);
    return null;
  }
}

/**
 * 测试靓号地址生成API
 */
async function testPrettyAddressAPI() {
  console.log('🎯 测试靓号地址生成API...\n');

  // 1. 测试难度估算
  console.log('📊 1. 测试难度估算');
  try {
    const params = new URLSearchParams({
      prefix: '88',
      suffix: '',
      caseSensitive: 'false',
      threads: '1'
    });
    
    const estimateResponse = await makeRequest(`${API_BASE}/pretty-address/estimate?${params}`);

    if (estimateResponse.data.success) {
      const { difficulty, estimatedTimeFormatted, recommendation } = estimateResponse.data.data;
      console.log(`- 难度: ${difficulty}`);
      console.log(`- 预估时间: ${estimatedTimeFormatted}`);
      console.log(`- 建议: ${recommendation}`);
    }
  } catch (error) {
    console.error('估算失败:', error.message);
  }

  console.log('\n🔍 2. 测试配置验证');
  try {
    const validateResponse = await makeRequest(`${API_BASE}/pretty-address/validate`, {
      method: 'POST',
      data: {
        prefix: '88',
        suffix: '',
        caseSensitive: false,
        threads: 1
      }
    });

    if (validateResponse.data.valid) {
      console.log('✅ 配置验证通过');
      console.log(`- 详细信息: ${JSON.stringify(validateResponse.data.details, null, 2)}`);
    } else {
      console.log('❌ 配置验证失败:', validateResponse.data.message);
    }
  } catch (error) {
    console.error('验证失败:', error.message);
  }

  console.log('\n⚡ 3. 测试快速生成（简单前缀）');
  try {
    const generateResponse = await makeRequest(`${API_BASE}/pretty-address/generate`, {
      method: 'POST',
      data: {
        prefix: '1',
        suffix: '',
        caseSensitive: false,
        threads: 1,
        maxAttempts: 50000
      }
    });

    if (generateResponse.data.success) {
      const result = generateResponse.data.data;
      console.log('✅ 生成成功!');
      console.log(`- 地址: ${result.publicKey}`);
      console.log(`- 尝试次数: ${result.attempts}`);
      console.log(`- 耗时: ${result.timeElapsed}ms`);
      console.log(`- 难度: ${result.difficulty}`);
    } else {
      console.log('❌ 生成失败:', generateResponse.data.error);
    }
  } catch (error) {
    console.error('生成失败:', error.message);
  }
}

/**
 * 创建多种配置的代币
 */
async function createMultipleAdvancedTokens() {
  console.log('🔥 批量创建多种配置的代币...\n');

  const tokenConfigs = [
    {
      name: '简单代币',
      symbol: 'SIMPLE',
      decimals: 6,
      supply: '1000000',
      description: '简单配置的代币',
      enablePrettyAddress: false,
      revokeUpdateAuthority: false,
      revokeFreezeAuthority: false,
      revokeMintAuthority: false,
    },
    {
      name: '社交代币',
      symbol: 'SOCIAL',
      decimals: 9,
      supply: '100000000',
      description: '包含社交链接的代币',
      enablePrettyAddress: false,
      website: 'https://social-token.com',
      twitter: 'https://twitter.com/socialtoken',
      telegram: 'https://t.me/socialtoken',
      revokeUpdateAuthority: false,
      revokeFreezeAuthority: true,
      revokeMintAuthority: false,
    },
    {
      name: '安全代币',
      symbol: 'SECURE',
      decimals: 9,
      supply: '50000000',
      description: '高安全性配置的代币',
      enablePrettyAddress: false,
      revokeUpdateAuthority: true,
      revokeFreezeAuthority: true,
      revokeMintAuthority: true,
    }
  ];

  const results = [];

  for (let i = 0; i < tokenConfigs.length; i++) {
    const config = {
      ...tokenConfigs[i],
      creator: CREATOR_ADDRESS
    };

    console.log(`\n📍 === 创建代币 ${i + 1}/${tokenConfigs.length}: ${config.name} ===`);
    
    try {
      const response = await makeRequest(`${API_BASE}/api/tokens`, {
        method: 'POST',
        data: config
      });
      
      if (response.data.success) {
        const { token } = response.data.data;
        console.log(`✅ ${config.name} 创建成功: ${token.mint}`);
        results.push({ success: true, token, config });
      } else {
        console.log(`❌ ${config.name} 创建失败: ${response.data.error}`);
        results.push({ success: false, error: response.data.error, config });
      }
    } catch (error) {
      console.log(`❌ ${config.name} 请求失败: ${error.message}`);
      results.push({ success: false, error: error.message, config });
    }

    // 请求间隔
    if (i < tokenConfigs.length - 1) {
      console.log('⏳ 等待 3 秒后创建下一个代币...');
      await new Promise(resolve => setTimeout(resolve, 3000));
    }
  }

  // 生成总结报告
  console.log('\n📊 === 批量创建总结 ===');
  const successful = results.filter(r => r.success);
  const failed = results.filter(r => !r.success);

  console.log(`✅ 成功: ${successful.length}/${results.length}`);
  console.log(`❌ 失败: ${failed.length}/${results.length}`);

  if (successful.length > 0) {
    console.log('\n🎉 成功创建的代币:');
    successful.forEach((result, index) => {
      console.log(`${index + 1}. ${result.token.name} (${result.token.symbol}): ${result.token.mint}`);
    });
  }

  if (failed.length > 0) {
    console.log('\n❌ 失败的代币:');
    failed.forEach((result, index) => {
      console.log(`${index + 1}. ${result.config.name}: ${result.error}`);
    });
  }

  // 保存批量创建结果
  fs.writeFileSync(`batch-token-creation-${Date.now()}.json`, JSON.stringify(results, null, 2));
  console.log('\n💾 批量创建结果已保存');

  return results;
}

// 主函数
async function main() {
  const command = process.argv[2] || 'advanced';

  console.log('🎯 高级代币创建测试工具\n');

  switch (command) {
    case 'advanced':
      console.log('🚀 单个高级代币创建');
      await createAdvancedToken();
      break;

    case 'pretty':
      console.log('🎨 靓号地址API测试');
      await testPrettyAddressAPI();
      break;

    case 'batch':
      console.log('🔥 批量代币创建');
      await createMultipleAdvancedTokens();
      break;

    case 'all':
      console.log('🌟 完整功能测试');
      await testPrettyAddressAPI();
      console.log('\n' + '='.repeat(50) + '\n');
      await createAdvancedToken();
      console.log('\n' + '='.repeat(50) + '\n');
      await createMultipleAdvancedTokens();
      break;

    default:
      console.log('📋 可用命令:');
      console.log('- advanced: 创建一个高级功能代币');
      console.log('- pretty: 测试靓号地址生成API');
      console.log('- batch: 批量创建多种配置的代币');
      console.log('- all: 运行所有测试');
      console.log('\n示例:');
      console.log('node scripts/test-advanced-token-creation.js advanced');
      console.log('node scripts/test-advanced-token-creation.js pretty');
      console.log('node scripts/test-advanced-token-creation.js batch');
  }
}

if (require.main === module) {
  main().catch(console.error);
}

module.exports = {
  createAdvancedToken,
  testPrettyAddressAPI,
  createMultipleAdvancedTokens
};
